<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input
            placeholder="请输入用户名"
            v-model="userNameSearch"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="search()"
            :disabled="userNameSearch ? false : true"
          >
            搜索
          </el-button>
          <el-button @click="resetting">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button @click="addUser()" icon="Plus">添加</el-button>
      <el-button
        @click="delAllList"
        :disabled="tableUser.length ? false : true"
      >
        批量删除
      </el-button>
      <!-- table展示用户 -->
      <el-table
        style="margin: 10px 0"
        border
        :data="userDataList"
        :fit="false"
        @select="select"
        @select-all="selectAll"
      >
        <el-table-column
          type="selection"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="#"
          align="center"
          min-width="50px"
          type="index"
        ></el-table-column>
        <el-table-column
          label="ID"
          align="center"
          min-width="100px"
          prop="id"
        ></el-table-column>
        <el-table-column
          label="用户名字"
          align="center"
          min-width="150px"
          prop="username"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          min-width="150px"
          prop="name"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          min-width="150px"
          prop="roleName"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          min-width="170px"
          prop="createTime"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          min-width="170px"
          prop="updateTime"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="操作" align="center" min-width="400px">
          <template #default="{ row }">
            <el-button icon="User" @click="allocation(row)" type="primary">
              分配角色
            </el-button>
            <el-button icon="Edit" @click="edit(row)">编辑</el-button>

            <el-popconfirm title="是否删除?" @confirm="delUser(row)">
              <template #reference>
                <el-button icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <!-- 分页组件 -->
      <Pagination
        v-model:page="currentPage"
        v-model:size="pageSize"
        :total="total"
        :background="true"
        @pagination="list"
        @paginations="paginations"
      ></Pagination>
    </el-card>
    <!-- 添加/修改 抽屉 -->
    <el-drawer v-model="drawer" :lock-scroll="true">
      <template #header>
        <h4>{{ userParams.id ? '修改用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form ref="formRef" :model="userParams" :rules="rules">
          <el-form-item label="用户名字" prop="username">
            <el-input
              placeholder="请输入用户名字"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input
              placeholder="请输入用户名称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="角色列表"></el-form-item> -->
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button @click="save" type="primary">确定</el-button>
      </template>
    </el-drawer>
    <!-- 分配角色 抽屉 -->
    <el-drawer v-model="allocationIf">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="角色名称">
            <el-input
              placeholder="角色名称"
              :disabled="true"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="职位名称">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="indeterminate"
              @change="checkboxAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="userAllRole"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(item, index) in allRole"
                :key="index"
                :label="item"
              >
                {{ item.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="roleCancel">取消</el-button>
        <el-button @click="roleSave" type="primary">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import userLayoutStore from '@/store/modules/setting.ts'
import Pagination from '@/components/pagination/index.vue'
import { onMounted, reactive, ref, nextTick } from 'vue'
import {
  userList,
  userAddEdit,
  reqAllRole,
  reqSetUserRole,
  reqDelUser,
  reqAllDelUser,
} from '@/api/acl/user/index'
import type { FormRules } from 'element-plus'
import type {
  userCode,
  userCodes,
  userDataRecords,
  userRole,
  AllRolesList,
  setRoleData,
  successCode,
} from '@/api/acl/user/type.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
// 默认页码
let currentPage = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>(0)
// 用户数据
let userDataList = ref<userDataRecords[]>()
// 响应式控制抽屉
let drawer = ref<boolean>(false)
// 收集用户信息
let userParams = reactive<userDataRecords>({
  username: '',
  password: '',
  name: '',
})
// 分配角色抽屉控制
let allocationIf = ref<boolean>(false)
// 全选按钮
let checkAll = ref<boolean>(false)
let indeterminate = ref<boolean>(false)
// 单选按钮
let allRole = ref<AllRolesList[]>([])
// 已勾选
let userAllRole = ref<AllRolesList[]>([])
// table选择用户数据
let tableUser = ref<number[]>([])
// 用户搜索input
let userNameSearch = ref<string>('')
// 获取刷新仓库
let settingStore = userLayoutStore()
// 表单校验
let formRef = ref<any>()
const rulesUserName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字最少五位'))
  }
}
const rulesName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名称最少五位'))
  }
}
const rulesPassWord = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码最少六位'))
  }
}
const rules = reactive<FormRules<userDataRecords>>({
  username: [{ required: true, trigger: 'blur', validator: rulesUserName }],
  name: [{ required: true, trigger: 'blur', validator: rulesName }],
  password: [{ required: true, trigger: 'blur', validator: rulesPassWord }],
})
//进入页面获取列表数据
const list = async () => {
  let res: userCode = await userList(
    currentPage.value,
    pageSize.value,
    userNameSearch.value,
  )
  userDataList.value = res.data.records
  total.value = res.data.total
}
onMounted(() => {
  list()
})
const paginations = () => {
  currentPage.value = 1
  list()
}
// 添加用户
const addUser = () => {
  drawer.value = true
  Object.assign(userParams, {
    id: 0,
    username: '',
    password: '',
    name: '',
  })
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
// 编辑用户
const edit = (val: userDataRecords) => {
  Object.assign(userParams, JSON.parse(JSON.stringify(val)))
  drawer.value = true
  formRef.value?.clearValidate('username')
  formRef.value?.clearValidate('name')
  formRef.value?.clearValidate('password')
}
// 编辑取消
const cancel = () => {
  drawer.value = false
}
// 编辑确定
const save = async () => {
  await formRef.value.validate()
  let res: userCodes = await userAddEdit(userParams)
  if (res.code == 200) {
    drawer.value = false
    ElMessage.success(userParams.id ? '修改成功' : '新增成功')
    //更改完用户信息自动让浏览器刷新
    window.location.reload()
  } else {
    ElMessage.error(userParams.id ? '修改失败' : '新增失败')
  }
}
// 分配角色
const allocation = async (val: userDataRecords) => {
  Object.assign(userParams, JSON.parse(JSON.stringify(val)))
  let res: userRole = await reqAllRole(userParams.id as number)
  if (res.code == 200) {
    allRole.value = res.data.allRolesList
    userAllRole.value = res.data.assignRoles
    allocationIf.value = true
  }
}
// 全选框change事件
const checkboxAllChange = (val: boolean) => {
  userAllRole.value = val ? allRole.value : []
  indeterminate.value = false
}
// 单选框change事件
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  indeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}
// 分配角色确定
const roleSave = async () => {
  let data: setRoleData = {
    userId: userParams.id as number,
    roleIdList: userAllRole.value.map((item) => item.id),
  }
  if (data.roleIdList.length) {
    let res: successCode = await reqSetUserRole(data)
    if (res.code == 200) {
      ElMessage.success('分配成功')
      allocationIf.value = false
      list()
    } else {
      ElMessage.error('分配角色失败')
    }
  } else {
    ElMessage.error('请至少勾选一个角色')
  }
}
// 分配角色取消
const roleCancel = () => {
  allocationIf.value = false
  checkAll.value = false
  indeterminate.value = false
}
// 删除
const delUser = async (val: userDataRecords) => {
  let res: successCode = await reqDelUser(val.id as number)
  if (res.code == 200) {
    ElMessage.success('删除成功')
    list()
  } else {
    ElMessage.error('删除失败')
  }
}
// 批量删除
const delAllList = () => {
  ElMessageBox.confirm('是否删除选中的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    let res: successCode = await reqAllDelUser(tableUser.value)
    if (res.code == 200) {
      ElMessage.success('批量删除成功')
      list()
    } else {
      ElMessage.error('批量删除失败')
    }
  })
}

// table单选
const select = (val: userDataRecords[]) => {
  tableUser.value = val.map((item) => item.id) as number[]
}
// table单选
const selectAll = (val: userDataRecords[]) => {
  tableUser.value = val.map((item) => item.id) as number[]
}
//搜索
const search = () => {
  list()
  userNameSearch.value = ''
}
// 重置
const resetting = () => {
  settingStore.refsh = !settingStore.refsh
}
</script>
<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
